package com.yxinsur.imc.web.controller.business;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

import com.yxinsur.imc.business.domain.ImcBroker;
import com.yxinsur.imc.business.domain.ImcTeam;
import com.yxinsur.imc.business.excel.TeamTemplate;
import com.yxinsur.imc.business.form.BrokerSearchForm;
import com.yxinsur.imc.business.form.TeamForm;
import com.yxinsur.imc.business.mapper.ImcTeamMapper;
import com.yxinsur.imc.business.service.IImcBrokerService;
import com.yxinsur.imc.business.service.IImcTeamService;
import com.yxinsur.imc.business.vo.TeamVo;
import com.yxinsur.imc.common.core.domain.entity.SysOrg;
import com.yxinsur.imc.common.core.domain.model.LoginUser;
import com.yxinsur.imc.common.utils.SecurityUtils;
import com.yxinsur.imc.common.utils.ServletUtils;
import com.yxinsur.imc.framework.web.service.TokenService;
import com.yxinsur.imc.system.mapper.SysOrgMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.yxinsur.imc.common.annotation.Log;
import com.yxinsur.imc.common.core.controller.BaseController;
import com.yxinsur.imc.common.core.domain.AjaxResult;
import com.yxinsur.imc.common.enums.BusinessType;
import com.yxinsur.imc.common.utils.poi.ExcelUtil;
import com.yxinsur.imc.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 营销区-团队Controller
 *
 * @author imc
 * @date 2021-03-23
 */
@Api(value = "营销团队模块接口服务", tags = {"营销团队模块接口服务"})
@RestController
@RequestMapping("/business/team")
public class ImcTeamController extends BaseController {
    @Autowired
    private IImcTeamService imcTeamService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private ImcTeamMapper imcTeamMapper;
    @Autowired
    private SysOrgMapper sysOrgMapper;
    @Autowired
    private IImcBrokerService iImcBrokerService;

    /**
     * 查询营销区-团队列表
     */
    //@PreAuthorize("@ss.hasPermi('system:team:list')")
    @ApiOperation("查询营销团队")
    @GetMapping("/list")
    public TableDataInfo list(TeamForm imcTeam) {
        Long orgId = imcTeam.getOrgId();
        if(orgId==null){
            String authOrgIds = SecurityUtils.getLoginUser().getAuthOrgIds();
            String[] split = authOrgIds.split(",");
            List<String> orgStrList = Arrays.asList(split);
            List<Long> collect = orgStrList.stream().map(Long::parseLong).collect(Collectors.toList());
            imcTeam.setOrgIds(collect);
        }else{
            List<SysOrg> sysOrgs = sysOrgMapper.selectChildrenOrgById(orgId);
            List<Long> orgIds = sysOrgs.stream().map(SysOrg::getOrgId).collect(Collectors.toList());
            orgIds.add(orgId);
            imcTeam.setOrgIds(orgIds);
        }
        startPage();
        List<TeamVo> list = imcTeamService.selectImcTeamList(imcTeam);
        return getDataTable(list);
    }

    /**
     * 获取营销区-团队详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:team:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(imcTeamService.selectImcTeamById(id));
    }

    /**
     * 新增营销区-团队
     */
    //@PreAuthorize("@ss.hasPermi('system:team:add')")
    @ApiOperation("新增营销团队")
    @Log(title = "营销区-团队", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult add(@RequestBody TeamForm imcTeam) {
        return toAjax(imcTeamService.insertImcTeam(imcTeam));
    }

    /**
     * 修改营销区-团队
     */
    @ApiOperation("修改营销团队")
    //@PreAuthorize("@ss.hasPermi('system:team:edit')")
    @Log(title = "营销区-团队", businessType = BusinessType.UPDATE)
    @PutMapping("/edit")
    public AjaxResult edit(@RequestBody TeamForm imcTeam) {
        return toAjax(imcTeamService.updateImcTeam(imcTeam));
    }


    /**
     * 团队信息导出
     */
    @ApiOperation("团队信息导出")
    @Log(title = "代理人信息", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TeamForm teamForm) {
        Long orgId = teamForm.getOrgId();
        if(orgId==null){
            String authOrgIds = SecurityUtils.getLoginUser().getAuthOrgIds();
            String[] split = authOrgIds.split(",");
            List<String> orgStrList = Arrays.asList(split);
            List<Long> collect = orgStrList.stream().map(Long::parseLong).collect(Collectors.toList());
            teamForm.setOrgIds(collect);
        }else{
            List<SysOrg> sysOrgs = sysOrgMapper.selectChildrenOrgById(orgId);
            List<Long> orgIds = sysOrgs.stream().map(SysOrg::getOrgId).collect(Collectors.toList());
            orgIds.add(orgId);
            teamForm.setOrgIds(orgIds);
        }
        List<TeamVo> list = imcTeamService.selectExportImcTeamList(teamForm);
        ExcelUtil<TeamVo> util = new ExcelUtil<TeamVo>(TeamVo.class);
        return util.exportExcel(list, "团队信息");
    }

    /**
     * 团队信息模板导出
     */
    @ApiOperation(value = "团队信息模板导出", produces = "application/octet-stream")
    @GetMapping("/importTemplate")
    public AjaxResult importTemplate() {
        ExcelUtil<TeamTemplate> util = new ExcelUtil<TeamTemplate>(TeamTemplate.class);
        return util.importTemplateExcel("团队信息模板");
    }

    @ApiOperation(value = "团队信息导入")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<TeamTemplate> util = new ExcelUtil<TeamTemplate>(TeamTemplate.class);
        List<TeamTemplate> imcTeamList = util.importExcel(file.getInputStream());
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        String operName = loginUser.getUsername();
        HashMap<String, Object> resultMap = imcTeamService.checkImportTeam(imcTeamList);
        if ((boolean) resultMap.get("flag")) {
            String message = imcTeamService.importTeam(imcTeamList, updateSupport, operName);
            return AjaxResult.success(message);
        } else {
            return AjaxResult.error((String)resultMap.get("message"));
        }

    }


    /**
     * 删除营销区-团队
     */
    @ApiOperation(value = "删除营销区-团队")
    @Log(title = "营销区-团队", businessType = BusinessType.DELETE)
    @DeleteMapping("/{id}")
    public AjaxResult deleteTeam(@PathVariable("id") Long id) {
        //团队下有人不能删除
        List<ImcBroker> brokers = iImcBrokerService.selectBrokerByTeamId(id);
        if(!CollectionUtils.isEmpty(brokers)){
            return AjaxResult.error("团队下存在代理人，不能删除");
        }
        //团队有下级团队不能删除
        List<TeamVo> teamVos = imcTeamMapper.selectImcTeamByParentId(id);
        if(!CollectionUtils.isEmpty(teamVos)){
            return AjaxResult.error("团队存在下级团队，不能删除");
        }
        return toAjax(imcTeamService.deleteTeam(id));
    }
}
